const iframeHttp = (options) => {
    if (!document.body) {
        throw Error('必须在html加载完毕后使用');
    };
    const d = document.body;
    let opt = Object.assign({
        url: 'https://a.test.com',
        method: 'post',
        proxyUrl: 'https://a.test.com/proxy',
        successFn: () => {},
        failFn: () => {},
    }, options);
    let pre_txt = new Date().getTime();
    window['callback_' + pre_txt] = function(data) {
        opt.successFn(data);
    };
    createDom(pre_txt, opt);

};

function createDom(pre_txt, opt) {
    // 内嵌iframe
    const _iframe = document.createElement('iframe');
    _iframe.id = 'iframe_' + pre_txt;
    _iframe.name = 'iframe_name_' + pre_txt;
    d.appendChild(_iframe);
     // 发请求使用的form
    const _iform = document.createElement('form');
    _iform.id = 'iform_' + pre_txt;
    _iform.action = opt.url;
    _iform.method = opt.method;
    _iform.target = _iframe;
    d.appendChild(_iform);
    const input_callback = document.createElement('input');
    const input_proxy = document.createElement('input');
    input_callback.type = 'text';
    input_callback.name = 'callback';
    input_callback.value = 'callback_' + pre_txt;
    input_proxy.type = 'text';
    input_proxy.name = 'proxy';
    input_proxy.value = opt.proxyUrl;
    _iform.appendChild(input_callback);
    _iform.appendChild(input_proxy);
    _iform.submit();
}


function inner_html() {
    window.onload = function() {
        if (top === self) return;
        let fn,
            ags;
        let arr = location.search.substring(1).split('&');
        for(var i = 0; i < arr.length; i++) {
            item = arr[i].split('=');
            if (item[0] === 'callback') {
                fn = item[1];
            } else if (item[0] === 'ags') {
                ags = item[1];
            }
        };
        try {
            eval('top.' + fn + '("' + ags + '")');
        } catch (error) {
            console.log('err:', error);
        }
    }
}

export const crossHttps = {
    iframeHttp,
}